//
//  PhotoBrowserViewController.swift
//  我的微博
//
//  Created by teacher on 15/8/8.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 可重用标示符
private let HMPhotoBrowserViewCell = "HMPhotoBrowserViewCell"

class PhotoBrowserViewController: UIViewController {

    // MARK: - 属性
    /// URL 的数组
    var urls: [NSURL]
    /// 用户当前选中的照片索引值
    var selectedIndex: Int
    
    init(urls: [NSURL], index: Int) {
        
        // 给自己的属性设置数值
        self.urls = urls
        selectedIndex = index
        
        // 调用父类的构造函数
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        print(urls)
    }
    
    // MARK: - 按钮监听方法
    /// 关闭
    func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 保存
    func save() {
        // TODO: 保存照片
        print(__FUNCTION__)
        
        // 1. 获取照片
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoBrowserCell
        
        // 要判断图像视图中是否存在图像，因为 sdwebImage 不一定能够下载到图像
        guard let image = cell.imageView.image else {
            return
        }
        
        // 2. 保存
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        print(error)
        print(image)
        
        let msg = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(msg)
    }
    
    // 提示：所有成熟的第三方框架中，只有sdwebimage支持gif播放！但是内存消耗非常大！
    // 如果使用自动布局，在拖动cell的时候，会被重新调用，造成照片错位
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // 跳转到用户选中的照片
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    // 跳转界面一定不要在 didAppear 方法中执行，视图出现首先就会显示第一张图片，造成跳跃的情况
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 跳转到用户选中的照片
        // let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        // collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    // MARK: - 构造函数
    override func loadView() {
        // 提示：尺寸很重要
        var screenBounds = UIScreen.mainScreen().bounds
        screenBounds.size.width += 20
        
        view = UIView(frame: screenBounds)
        
        setupUI()
    }
    
    private func setupUI() {
        // 1. 添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 2. 设置控件位置
        collectionView.frame = view.bounds
        
        let rect = CGRect(x: 0, y: UIScreen.mainScreen().bounds.height - 40, width: 100, height: 32)
        closeButton.frame = CGRectOffset(rect, 8, 0)
        saveButton.frame = CGRectOffset(rect, UIScreen.mainScreen().bounds.width - rect.width - 8, 0)
     
        // 3. 监听方法
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 4. 设置独立控件属性
        prepareCollectionView()
    }
    
    /// 准备 CollectionView
    private func prepareCollectionView() {
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: HMPhotoBrowserViewCell)
        collectionView.dataSource = self
        
        // 设置布局
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        // collectionView 的大小同样会宽 20 个点
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }
    
    // MARK: - 懒加载
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    
    /// 视图缩放比例
    private var photoScale: CGFloat = 1
}

// MARK: - UICollectionViewDataSource
extension PhotoBrowserViewController: UICollectionViewDataSource, PhotoBrowserCellDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMPhotoBrowserViewCell, forIndexPath: indexPath) as! PhotoBrowserCell
        
        cell.imageURL = urls[indexPath.item]
        cell.photoDelegate = self
        
        return cell
    }
    
    // MARK: - PhotoBrowserCellDelegate
    /// 缩放进行中
    func photoBrowserCellZoom(scale: CGFloat) {
        print(scale)
        // 交互式专场 - 遵守协议
        // 记录缩放比例
        photoScale = scale
        
        // 设置控件的隐藏
        hiddenControls(scale < 1)
        // 开始转场
        if scale < 1.0 {
            startInteractiveTransition(self)
        } else {
            view.transform = CGAffineTransformIdentity
            view.alpha = 1
        }
    }
    
    /// 缩放完成
    func photoBrowserCellEndZoom() {
        // 判断缩放比例
        if photoScale < 0.8 {
            // 结束转场
            completeTransition(true)
        } else {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1
                
                }, completion: { (_) -> Void in
                    self.photoScale = 1
                    self.hiddenControls(false)
            })
        }
    }
    
    /// 当前显示的图像视图
    func currentImageView() -> UIImageView {
        let cell = collectionView.cellForItemAtIndexPath(currentImageIndex()) as! PhotoBrowserCell
        
        return cell.imageView
    }
    
    /// 当前显示的照片索引
    func currentImageIndex() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems().last!
    }
    
    /// 隐藏控件
    private func hiddenControls(hidden: Bool) {
        collectionView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()
        closeButton.hidden = hidden
        saveButton.hidden = hidden
    }
}

// MARK: - UIViewControllerInteractiveTransitioning
extension PhotoBrowserViewController: UIViewControllerInteractiveTransitioning {
    
    /// 开始交互专场
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 设置形变
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        // 设置透明度
        view.alpha = photoScale
    }
}

// MARK: UIViewControllerContextTransitioning context 提供了转场所需的所有细节！
extension PhotoBrowserViewController: UIViewControllerContextTransitioning {
    
    /// 结束专场动画
    func completeTransition(didComplete: Bool) {
        // 关闭当前的控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 容器视图
    func containerView() -> UIView? { return view.superview }
    
    func isAnimated() -> Bool { return true }
    func isInteractive() -> Bool { return true }
    func transitionWasCancelled() -> Bool { return false }
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }

    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewControllerForKey(key: String) -> UIViewController? { return self }
    func viewForKey(key: String) -> UIView? { return view }
    func targetTransform() -> CGAffineTransform { return CGAffineTransformIdentity }
    func initialFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
    func finalFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
}
